//App: Form validator based on the Mootools framework
//Author: Brendan Morante
//Updated: 10/16/2006
var MooForm = new Class.create({
	
	initialize: function(form) {
		this.errors = [];
		this.form = $(form);
		this.formEls = $ES("input, select, textarea",this.form);//this.form.getElementsBySelector("input, select, textarea");
		this.requiredEls = new Array();
		this.formEls.each(function(el) { 
			if(el.hasClass("required")) this.requiredEls.push(el)
		},this);
	},
	
	validateForm: function() {
		var valid = true;
		this.errors = [];
		this.requiredEls.each(function(el) {
			
			if(el.hasClass("email")) {
				this.checkEmail(el);
			}
			if(el.hasClass("phone")) {
				this.checkPhone(el);
			}
			if(!el.hasClass("phone") && !el.hasClass("email")) {
				this.hasValue(el);
			}
		}, this);
		if(this.errors.length > 0) {
			return false;
		}
		else {
			return true;
		}
	},
	
	disableForm: function() {
		var els = $ES("input, select, textarea",this.form);
		els.each(function(el) {
			el.disabled = true;
		});
	},
	
	enableForm: function() {
		var els = $ES("input, select, textarea",this.form);
		els.each(function(el) {
			el.disabled = false;
		});
	},
	
	checkEmail: function(el) {
		
		var emailFilter="^.+@.+\..{2,3}$";
		var illegalChars= /[\(\)\<\>\,\;\:\\\/\"\[\]]/;
		var value = el.value;
		var valid = true;
		if (!(value.test(emailFilter)) { 
			this.errors.push({element:el, message: "Invalid Email Address"});
			valid = false;
		}
		if (value.match(illegalChars)) {
			this.errors.push({element:el, message: "The email address contains illegal characters."});
			valid = false;
		}
		return valid;
	},
	
	checkPhone: function(el) {
		var value = el.getValue(el);
		var valid = true;
		var stripped = value.replace(/[\(\)\.\-\ ]/g, '');
		//strip out acceptable non-numeric characters
		if (!((stripped)+1 > 0)) {
		   this.errors.push({element:el, message:"The phone number contains illegal characters."});
		   valid = false;
		}
		if (!(stripped.length == 10)) {
			this.errors.push({element:el, message:"The phone number is the wrong length. Make sure you included an area code."});
			valid = false;
		}
		return valid;
	},
	
	hasValue: function(el) {
		var value = this.getValue(el);
		if(value.replace(/^\s*|\s*$/g,"").length == 0) {
			this.errors.push({element:el, message:"Field was left blank."});
			return false;
		}
		else {
			return true;
		}
	},
	
	
	clearForm: function() {
		$ES("input, select, textarea",this.form).each(function(el) {
			if(el.value) el.value = '';
		});
	}
});